/**
 * 医院站点管理 Hook
 */

import { useState, useEffect, useCallback } from 'react'
import { hospitalAPI, HospitalSite as APIHospitalSite } from '@/lib/api/hospital'

export interface HospitalSite {
  id: string
  name: string
  center: [number, number]
  zoom: number
  address?: string
  district?: string
  city?: string
  province?: string
}

export function useHospitalSites() {
  const [sites, setSites] = useState<HospitalSite[]>([])
  const [isLoading, setIsLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)

  // 从API数据转换为本地格式
  const convertAPIToLocal = useCallback((apiSite: APIHospitalSite): HospitalSite => {
    return {
      id: apiSite.siteId,
      name: apiSite.name,
      center: [apiSite.coordinates.longitude, apiSite.coordinates.latitude],
      zoom: apiSite.zoom || 16,
      address: apiSite.address,
      district: apiSite.district,
      city: apiSite.city,
      province: apiSite.province
    }
  }, [])

  // 加载医院站点
  const loadSites = useCallback(async () => {
    setIsLoading(true)
    setError(null)

    try {
      const response = await hospitalAPI.getSites({
        status: 'active',
        limit: 100
      })

      if (response?.success && response?.data?.sites) {
        const localSites = response.data.sites.map(convertAPIToLocal)
        setSites(localSites)
        
        // 同时更新本地存储作为缓存
        localStorage.setItem('hospital_sites', JSON.stringify(localSites))
      }
    } catch (err) {
      const errorMsg = err instanceof Error ? err.message : '加载医院站点失败'
      setError(errorMsg)
      console.error('加载医院站点失败:', err)
      
      // 如果API失败，尝试从本地存储加载
      try {
        const cachedSites = localStorage.getItem('hospital_sites')
        if (cachedSites) {
          setSites(JSON.parse(cachedSites))
        }
      } catch (cacheError) {
        console.error('加载缓存数据失败:', cacheError)
      }
    } finally {
      setIsLoading(false)
    }
  }, [convertAPIToLocal])

  // 初始化加载
  useEffect(() => {
    loadSites()
  }, [loadSites])

  // 刷新站点数据
  const refreshSites = useCallback(() => {
    return loadSites()
  }, [loadSites])

  // 更新站点列表
  const updateSites = useCallback((newSites: HospitalSite[]) => {
    setSites(newSites)
    // 更新本地存储
    localStorage.setItem('hospital_sites', JSON.stringify(newSites))
  }, [])

  return {
    sites,
    isLoading,
    error,
    refreshSites,
    updateSites
  }
}